package com.ly.core.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.ly.core.model.OnlineUser;
import com.ly.oa.model.system.AppRole;
import com.ly.oa.model.system.AppUser;

/**
 * 方便取得Spring容器，取得其他服务实例，必须在Spring的配置文件里进行配置 如：<bean id="appUtil"
 * class="com.ly.util.core.AppUtil"/>
 * 
 * @author csx
 * 
 */
public class AppUtil implements ApplicationContextAware {

	private static Log logger = LogFactory.getLog(AppUtil.class);
	// 存放在线用户,SessionId,OnlineUser
	private static Map<String, OnlineUser> onlineUsers = new LinkedHashMap<String, OnlineUser>();
	private static Map configMap = new HashMap();
	private static ApplicationContext appContext=null;
	private static ServletContext servletContext=null;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.appContext = applicationContext;
	}

	/**
	 * 系统的菜单的文档，当系统启动时， 由系统去解析menu.xml，并放置系统，供权限菜单使用
	 */
	private static Document menuDocument = null;

	public static Document getMenuDocument() {
		return menuDocument;
	}

	public static void setMenuDocument(Document doc) {
		menuDocument = doc;
	}

	/**
	 * 取得Bean
	 * 
	 * @param beanId
	 * @return
	 */
	public static Object getBean(String beanId) {
		return appContext.getBean(beanId);
	}

	/**
	 * 返回在线用户
	 * 
	 * @return
	 */
	public static Map<String, OnlineUser> getOnlineUsers() {
		return onlineUsers;
	}

	/**
	 * 移除在线用户
	 * 
	 * @param sessionId
	 */
	public static void removeOnlineUser(String sessionId) {
		onlineUsers.remove(sessionId);
	}

	public static void addOnlineUser(String sessionId, AppUser user) {

		OnlineUser onlineUser = new OnlineUser();

		onlineUser.setFullname(user.getFullname());
		onlineUser.setSessionId(sessionId);
		onlineUser.setUsername(user.getUsername());
		onlineUser.setUserId(user.getUserId());
		onlineUser.setDepPath("." + user.getDepartment().getPath());

		// TODO add userRoleIds
		Set<AppRole> roles = user.getRoles();
		StringBuffer roleIds = new StringBuffer(",");
		for (AppRole role : roles) {
			roleIds.append(role.getRoleId() + ",");
		}
		onlineUser.setRoleIds(roleIds.toString());
		onlineUser.setTitle(user.getTitle());
		onlineUsers.put(sessionId, onlineUser);

	}

	public static String getAppAbsolutePath() {
		return servletContext.getRealPath("/");
	}

	public static String getFlowFormAbsolutePath() {
		String path = (String) configMap.get("app.flowFormPath");
		if (path == null)
			path = "/WEB-INF/FlowForm/";
		return getAppAbsolutePath() + path;
	}
	 public static void init(ServletContext in_servletContext)
	  {
	    servletContext = in_servletContext;
	    String filePath = servletContext.getRealPath("/WEB-INF/classes/conf/");

	    Properties props = new Properties();
	    try {
	      InputStream is = new BufferedInputStream(new FileInputStream(filePath + "/config.properties"));
	      props.load(is);
	      Iterator it = props.keySet().iterator();
	      while (it.hasNext()) {
	        String key = (String)it.next();
	        configMap.put(key, props.get(key));
	      }
	    } catch (Exception ex) {
	      logger.error(ex.getMessage());
	    }
//	    reloadSysConfig();
//
//	    CompanyService companyService = (CompanyService)getBean("companyService");
//	    List cList = companyService.findCompany();
//	    if (cList.size() > 0) {
//	      Company company = (Company)cList.get(0);
//	      configMap.put("app.logoPath", company.getLogo());
//	      configMap.put("app.companyName", company.getCompanyName());
//	    }
//
//	    String xslStyle = servletContext.getRealPath("/js/menu") + "/menu-left.xsl";
//	    Document doc = getOrignalMenuDocument();
//	    try
//	    {
//	      Document finalDoc = XmlUtil.styleDocument(doc, xslStyle);
//	      setLeftMenuDocument(finalDoc);
//	    } catch (Exception ex) {
//	      logger.error("menux.xml trasform has error:" + ex.getMessage());
//	    }
//
//	    String publicStyle = servletContext.getRealPath("/js/menu") + "/menu-public.xsl";
//	    try {
//	      Document publicDoc = XmlUtil.styleDocument(doc, publicStyle);
//	      HashSet pubIds = new HashSet();
//	      Element rootEl = publicDoc.getRootElement();
//	      List idNodes = rootEl.selectNodes("/Menus//*");
//	      for (int i = 0; i < idNodes.size(); ++i) {
//	        Element el = (Element)idNodes.get(i);
//	        Attribute attr = el.attribute("id");
//	        if (attr != null) {
//	          pubIds.add(attr.getValue());
//	        }
//	      }
//
//	      setPublicMenuIds(pubIds);
//	      setPublicDocument(publicDoc);
//	    }
//	    catch (Exception ex) {
//	      logger.error("menu.xml + menu-public.xsl transform has error:" + ex.getMessage());
//	    }
	  }
	
}
